﻿//Copyright (c) 2009, Offbeat Guides
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are 
//permitted provided that the following conditions are met:
//
//* Redistributions of source code must retain the above copyright notice, this list of 
//conditions and the following disclaimer.
//
//* Redistributions in binary form must reproduce the above copyright notice, this list 
//of conditions and the following disclaimer in the documentation and/or other materials 
//provided with the distribution.
//
//* Neither the name of Offbeat Guides nor the names of its contributors may be used to 
//endorse or promote products derived from this software without specific prior written 
//permission.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
//EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
//OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
//SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
//SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
//OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
//HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 
//TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 
//EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

using System;
using System.Collections.Generic;
using System.Text;
using Amazon.Services;
using System.Xml.XPath;
using System.IO;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.Xml;
using System.Net;

namespace Amazon.Services.EC2
{
    public partial class Instance
    {
        #region Static Methods
        public static Instance GetCurrentInstance(AmazonAccount account)
        {
            if (Instance.CurrentInstance == null)
            {
                IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
                String ipaddress = hostEntry.AddressList[0].ToString();
                Instance[] instances = Instance.GetInstances(account);
                for (int i = 0; i < instances.Length; i++)
                {
                    if (String.IsNullOrEmpty(instances[i].PublicDnsName))
                        continue;
                    if (instances[i].State != InstanceStates.Running)
                        continue;

                    IPHostEntry instanceEntry = Dns.GetHostEntry(instances[i].PublicDnsName);
                    if (instanceEntry.AddressList[0].ToString().Equals(ipaddress, StringComparison.OrdinalIgnoreCase))
                    {
                        Instance.CurrentInstance = instances[i];
                        break;
                    }
                }
            }
            return Instance.CurrentInstance;
        }

        public static Instance Create(AmazonAccount account, Image image)
        {
            Instance[] instances = Instance.Create(account, image.Id, 1);
            if (instances == null || instances.Length == 0)
                throw new Exception("");
            return instances[0];
        }

        public static Instance[] Create(AmazonAccount account, Image image, Int32 count)
        {
            return Instance.Create(account, image.Id, count);
        }

        public static Instance Create(AmazonAccount account, String imageId)
        {
            Instance[] instances = Instance.Create(account, imageId, 1);
            if (instances == null || instances.Length == 0)
                throw new Exception("");
            return instances[0];
        }

        public static Instance[] Create(AmazonAccount account, String imageId, Int32 count)
        {
            List<Instance> instances = new List<Instance>();

            Dictionary<String, String> parameters = new Dictionary<String, String>();
            parameters.Add("ImageId", imageId);
            parameters.Add("MinCount", count.ToString());
            parameters.Add("MaxCount", count.ToString());
            parameters.Add("Action", "RunInstances");

            EC2QueryService client = new EC2QueryService(account);
            Response response = client.Invoke(parameters, null);
            if (response.Status != System.Net.HttpStatusCode.OK)
                throw new AmazonException("Unable to create instance", response.Status);

            // just some basic reader settings; mainly to prevents whitespace from being read
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;
            settings.IgnoreWhitespace = true;

            // tear is apart into the instances and return the list
            using (XmlReader reader = XmlTextReader.Create(new StringReader(response.Body), settings))
            {
                while (reader.ReadToFollowing("instancesSet"))
                {
                    reader.ReadStartElement("instancesSet");
                    {
                        while (reader.Name.Equals("item", StringComparison.OrdinalIgnoreCase) && reader.NodeType != XmlNodeType.EndElement)
                        {
                            Instance instance = new Instance(client);
                            (instance as IXmlSerializable).ReadXml(reader);
                            instances.Add(instance);
                        }
                    }
                    reader.ReadEndElement();
                }
            }

            return instances.ToArray();
        }

        public static void Destroy(AmazonAccount account, String instanceId)
        {
            Dictionary<String, String> parameters = new Dictionary<String, String>();
            parameters.Add("InstanceId.1", instanceId);
            parameters.Add("Action", "TerminateInstances");

            EC2QueryService client = new EC2QueryService(account);
            Response response = client.Invoke(parameters, null);
            if (response.Status != System.Net.HttpStatusCode.OK)
                throw new AmazonException("Unable to destroy instance", response.Status);
        }

        public static Instance[] GetInstances(AmazonAccount account)
        {
            return Instance.GetInstances(account, new String[0]);
        }

        public static Instance[] GetInstances(AmazonAccount account, params String[] instanceIds)
        {
            List<Instance> instances = new List<Instance>();

            // set up the parameters for the request
            Dictionary<String, String> parameters = new Dictionary<String, String>();
            for (int i = 0; i < instanceIds.Length; i++)
                parameters.Add("InstanceId." + (i + 1), instanceIds[i]);
            parameters.Add("Action", "DescribeInstances");

            // make RESTful service Request
            EC2QueryService client = new EC2QueryService(account);
            Response response = client.Invoke(parameters, null);
            if (response.Status != System.Net.HttpStatusCode.OK)
                throw new AmazonException("Unable to get listing of instances", response.Status);

            // just some basic reader settings; mainly to prevents whitespace from being read
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;
            settings.IgnoreWhitespace = true;

            // tear is apart into the instances and return the list
            using (XmlReader reader = XmlTextReader.Create(new StringReader(response.Body), settings))
            {
                while (reader.ReadToFollowing("instancesSet"))
                {
                    reader.ReadStartElement("instancesSet");
                    {
                        while (reader.Name.Equals("item", StringComparison.OrdinalIgnoreCase) && reader.NodeType != XmlNodeType.EndElement)
                        {
                            Instance instance = new Instance(client);
                            (instance as IXmlSerializable).ReadXml(reader);
                            instances.Add(instance);
                        }
                    }
                    reader.ReadEndElement();
                }
            }

            return instances.ToArray();
        }

        public static Instance[] GetInstances(AmazonAccount account, InstanceStates state, params String[] instanceIds)
        {
            List<Instance> instances = new List<Instance>();

            // set up the parameters for the request
            Dictionary<String, String> parameters = new Dictionary<String, String>();
            for (int i = 0; i < instanceIds.Length; i++)
                parameters.Add("InstanceId." + (i + 1), instanceIds[i]);
            parameters.Add("Action", "DescribeInstances");

            // make RESTful service Request
            EC2QueryService client = new EC2QueryService(account);
            Response response = client.Invoke(parameters, null);
            if (response.Status != System.Net.HttpStatusCode.OK)
                throw new AmazonException("Unable to get listing of instances", response.Status);

            // just some basic reader settings; mainly to prevents whitespace from being read
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;
            settings.IgnoreWhitespace = true;

            // tear is apart into the instances and return the list
            using (XmlReader reader = XmlTextReader.Create(new StringReader(response.Body), settings))
            {
                while (reader.ReadToFollowing("instancesSet"))
                {
                    reader.ReadStartElement("instancesSet");
                    {
                        while (reader.Name.Equals("item", StringComparison.OrdinalIgnoreCase) && reader.NodeType != XmlNodeType.EndElement)
                        {
                            Instance instance = new Instance(client);
                            (instance as IXmlSerializable).ReadXml(reader);
                            if (instance.State == state)
                                instances.Add(instance);
                        }
                    }
                    reader.ReadEndElement();
                }
            }

            return instances.ToArray();
        }
        #endregion
    }

    public enum InstanceStates : int
    {
        Pending = 0,
        Running = 16,
        ShuttingDown = 32,
        Terminated = 48
    }
}
